package com.my.lab.net;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ConnectException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

import org.json.JSONException;
import org.json.JSONObject;

import android.os.Handler;
import android.util.Log;

import com.my.lab.util.ConfigConstant;
import com.my.lab.util.InputStreamUtils;

public class TcpMonitorSocketThread implements Runnable {

    private static final String TAG = "TcpMonitorSocketThread";

    private Thread tcpThread = null;

    private ServerSocket socket;

    private Socket connnetSocket;

    private String sendIp;

    private InputStream is;

    private boolean onWork = true;
    
    private Handler callback;
    
    public TcpMonitorSocketThread(String sendIp) {
        this.sendIp = sendIp;
    }

    @Override
    public void run() {
        try {
            connnetSocket = new Socket(sendIp, ConfigConstant.TCP_CONNECTPORT);
            Log.d(TAG, "已连接上发送端");
            DataInputStream dis = new DataInputStream(connnetSocket.getInputStream());
            is = connnetSocket.getInputStream();
            JSONObject json = new JSONObject(InputStreamUtils.InputStreamTOString(is, "gbk"));
            callback.obtainMessage(1, json).sendToTarget();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                connnetSocket.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            connnetSocket = null;
        }

    }

    public void beginMonitorTcp(Handler callback) {
        this.callback = callback;
        if (tcpThread == null) {
            tcpThread = new Thread(this);
            tcpThread.start();
        }
    }

    public boolean isMonitoring() {
        if (tcpThread == null)
            return false;
        return true;
    }

    public void stopMonitorTcp() {
        onWork = false;
        if (tcpThread != null) {
            tcpThread.interrupt();
            tcpThread = null;
        }
    }

}
